package com.kyzh.core.activities

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import android.webkit.JavascriptInterface
import com.bytedance.applog.game.GameReportHelper
import com.google.gson.Gson
import com.gushenge.atools.util.ADate
import com.gushenge.atools.util.AView
import com.gushenge.core.base.Base
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.PayJuBean
import com.gushenge.core.dao.MMKVConsts.uid
import com.kyzh.core.R
import com.kyzh.core.utils.md5
import com.gushenge.core.toast
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.sdk.*
import kotlinx.android.synthetic.main.webview.*
import org.jetbrains.anko.browse
import java.util.*

@Suppress("DEPRECATION")
class H5Activity : BaseActivity() {

    private val mHomeUrl = "${Base.BASEURL}/?ct=h5login&gid="
    val BASEURL = "http://pay.94php.com"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.webview)
        val islande = intent.getStringExtra("heng")
        kotlin.runCatching {
            if(!islande.isNullOrEmpty()){
                requestedOrientation = if (islande == "1") {
                    ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                } else {
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

                }
            }

        }
        AView.fullScreen(this)
        val windows = window
        windows.setFormat(PixelFormat.TRANSLUCENT)
        windows.setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED)
        val map = mutableMapOf<String,Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)
        val gid = intent.getStringExtra("gid")
        val time = ADate.getStampAs13()
        val sign = md5("${uid}${time}fsd213ewdsadqwe2121213edsad")
        val url = "$mHomeUrl${gid}&uid=$uid&type=1&t=$time&sign=$sign"
        initUi(url)
    }
    inner class JsObject {
        @JavascriptInterface
        fun h5pay(msg : String){
            //商品类型，商品名称，商品ID，商品数量，支付渠道，币种，是否成功（必传），金额（必传）
            kotlin.runCatching {
                val fromJson = Gson().fromJson(msg, PayJuBean::class.java)
                //商品类型，商品名称，商品ID    ，商品数量，支付渠道，币种，是否成功（必传），金额（必传）
                GameReportHelper.onEventPurchase("coin","ptb", "",1, "wx","¥", true, fromJson.money);
            }

        }
    }
    @SuppressLint("SetJavaScriptEnabled")
    internal fun initUi(urlString: String) {
        val webSetting = webview.settings
        webview.addJavascriptInterface(JsObject(),"android")
        webSetting.allowFileAccess = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSetting.setSupportZoom(true)
        webSetting.builtInZoomControls = true
        webSetting.useWideViewPort = true
        webSetting.setSupportMultipleWindows(true)
        webSetting.setAppCacheEnabled(true)
        webSetting.domStorageEnabled = true
        webSetting.javaScriptEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(java.lang.Long.MAX_VALUE)
        webSetting.setAppCachePath(this.getDir("appcache", 0).path)
        webSetting.databasePath = this.getDir("databases", 0).path
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .path)
        webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
        webSetting.cacheMode = WebSettings.LOAD_NO_CACHE
        webSetting.javaScriptCanOpenWindowsAutomatically = true

        CookieSyncManager.createInstance(this)
        val cm = CookieManager.getInstance()
        cm.setAcceptCookie(true)
        CookieSyncManager.getInstance().sync()
        CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true)
        webview.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                //这里可以对特殊scheme进行拦截处理
                Log.e("TAG", "shouldOverrideUrlLoading: "+url )
                if (url != null) {
                    return if (url.startsWith("http")||url.startsWith("https")) {
                        //处理http和https开头的url
                        val extraHeaders = HashMap<String,String>()
                        extraHeaders["Referer"] = Base.BASEURL
                        view?.loadUrl(url, extraHeaders)
                        true
                    }else {
                        browse(url)
                        true
                    }
                }
                return true
            }
        }

        webview.loadUrl(urlString)

    }

    override fun onDestroy() {
        webview?.destroy()
        super.onDestroy()
    }

    override fun onBackPressed() {
        /*if (webview.canGoBack()) {
            webview.goBack()
        } else {*/
            exitByDoubleClick()
        //}
    }
    private var backPressedTime = System.currentTimeMillis()
    private fun exitByDoubleClick() {
        val nowTime = System.currentTimeMillis()
        if (nowTime - backPressedTime < 1500) {
            finish()
        } else {
            backPressedTime = nowTime
            getString(R.string.doubleTouchExitGame).toast()
        }
    }

    override fun onResume() {
        super.onResume()
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

    }

    override fun onPause() {
        super.onPause()
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }
}
